<template>
  <div class="message-page">
    <!-- 头部标题 -->
    <header class="xiaoxi-header">
      <div class="header-content">
        <!-- 返回按钮 -->
        <router-link to="/showshouye" class="go-back-btn"><</router-link>
        <!-- 标题 -->
        <h2 class="title">我的消息</h2>
        <!-- 一键全部已读按钮 -->
        <button class="mark-all-read-btn" @click="markAllAsRead">全部已读</button>
      </div>
    </header>

    <!-- 消息列表 -->
    <div class="message-list">
      <div
          class="message-item"
          v-for="(message, index) in messages"
          :key="index"
          @click="handleMessageClick(message)"
      >
        <div class="message-header">
          <el-icon><component :is="message.icon"></component></el-icon>
          <div class="message-title">{{ message.title }}</div>
          <div class="message-time">{{ message.time }}</div>
          <button class="delete-btn" @click.stop="deleteMessage(index)">×</button>
        </div>
        <div class="message-content">
          {{ message.text }}
        </div>

        <!-- 红点 -->
        <div v-if="!message.read" class="unread-badge"></div>
      </div>
    </div>

    <!-- 弹框展示视频内容 -->
    <el-dialog v-model="dialogVisible" title="视频内容" width="40%">
      <div v-if="selectedMessage && selectedMessage.title === '饿了美视频'">
        <p>点击下方按钮，在新窗口中查看视频：</p>
        <el-button type="primary" @click="openDouyinPage">查看视频</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElDialog, ElButton } from 'element-plus';
import { User, Box, VideoPlay, Shop } from '@element-plus/icons-vue';
import { useUserStore } from "../stores/user.ts";
import { storeToRefs } from "pinia";

const router = useRouter();
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

// 消息数据
const messages = ref([
  {
    icon: User,
    title: '饿了美钱包',
    text: '身份信息完善提醒',
    time: '星期四',
    read: false,
    contentUrl: ''
  },
  {
    icon: Box,
    title: '订单动态',
    text: '您订购的商品已准备好',
    time: '25/07/12',
    read: false,
    contentUrl: ''
  },
  {
    icon: VideoPlay,
    title: '饿了美视频',
    text: '你的主页Ta来过',
    time: '25/07/02',
    read: false,
    contentUrl: 'https://v.douyin.com/FdZ7en_3Tuc/' // 抖音视频链接
  },
  {
    icon: Shop,
    title: '隆江猪脚饭',
    text: '[自动回复]亲，您的订单已送出，配送小…',
    time: '25/06/07',
    read: false,
    contentUrl: ''
  }
]);

const selectedMessage = ref(null);
const dialogVisible = ref(false);

// 本地存储 key 前缀
const MESSAGE_STORAGE_KEY_PREFIX = 'user_messages_read_status_';

// 获取当前用户的 storage key
const getMessageStorageKey = () => {
  return userInfo.value ? `${MESSAGE_STORAGE_KEY_PREFIX}${userInfo.value.yhid}` : null;
};

// 保存已读状态到 localStorage
const saveReadStatus = () => {
  const storageKey = getMessageStorageKey();
  if (!storageKey) return;

  const status = messages.value.map(msg => msg.read);
  localStorage.setItem(storageKey, JSON.stringify(status));
};

// 加载本地已读状态
const loadReadStatus = () => {
  const storageKey = getMessageStorageKey();
  if (!storageKey) return;

  const savedStatus = JSON.parse(localStorage.getItem(storageKey));
  if (savedStatus) {
    messages.value = messages.value.map((msg, index) => ({
      ...msg,
      read: savedStatus[index] || false
    }));
  } else {
    // 如果没有记录，红点默认显示
    messages.value.forEach(msg => {
      msg.read = false;
    });
  }
};

// 打开抖音主页
const openDouyinPage = () => {
  if (selectedMessage.value && selectedMessage.value.contentUrl) {
    window.open(selectedMessage.value.contentUrl, '_blank');
  }
};

// 消息点击事件：标记为已读并处理特定消息
const handleMessageClick = async (message) => {
  message.read = true;
  saveReadStatus();

  if (message.title === '饿了美钱包') {
    // 跳转到 showuser 页面并定位到钱包部分
    router.push('/home/showuser');
  } else if (message.title === '饿了美视频') {
    selectedMessage.value = message;
    dialogVisible.value = true;
  } else if(message.title === '订单动态') {
    router.push('/home/showdd');
  }
};

// 删除消息按钮点击事件
const deleteMessage = (index) => {
  messages.value.splice(index, 1);
  saveReadStatus();
};

// 一键全部已读
const markAllAsRead = () => {
  messages.value.forEach(msg => {
    msg.read = true;
  });
  saveReadStatus();
};

// 用户切换时重新加载红点状态
watch(() => userInfo.value?.yhid, (newUserId) => {
  if (newUserId) {
    loadReadStatus();
  }
});

// 页面加载时读取红点状态
onMounted(() => {
  if (userInfo.value?.yhid) {
    loadReadStatus();
  }
});
</script>

<style scoped>
.xiaoxi-header {
  background-color: #f58147;
  color: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.title {
  margin: 0;
  font-size: 18px;
  flex: 1;
  text-align: center;
}

.go-back-btn {
  color: white;
  text-decoration: none;
  cursor: pointer;
}

.mark-all-read-btn {
  background-color: transparent;
  border: none;
  color: white;
  font-size: 14px;
  cursor: pointer;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  position: relative;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: background-color 0.2s;
}

.message-item:hover {
  background-color: #f9f9f9;
}

.unread-badge {
  position: absolute;
  top: 70%;
  right: 20px;
  transform: translateY(-50%);
  width: 8px;
  height: 8px;
  background-color: red;
  border-radius: 50%;
  z-index: 1;
}

.message-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.message-icon {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.message-title {
  font-size: 16px;
  font-weight: bold;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-content {
  font-size: 14px;
  color: #666;
}

.delete-btn {
  background-color: transparent;
  border: none;
  color: #ff4d4d;
  font-size: 16px;
  cursor: pointer;
}

/* 弹框样式 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #f58147;
  color: white;
  padding: 16px;
  border-bottom: 1px solid #ebebeb;
}

.el-dialog__title {
  margin: 0;
  font-size: 18px;
}

.el-dialog__body {
  padding: 20px;
}
</style>
